var chargingStationStatusData = [];
var webcamIndex = undefined;
var tableRefresh = true;
var time = undefined;
var onLineCount = undefined;
var startEchart = false;
var outputPowerData = [];
var powerRateData = [];
var outputMaxPower = 0;
var chargingChart = undefined;
var chargingDate = undefined;

$(document).ready(function() {
	showLoading();
	$('title', parent.document).html($('title').text());
	setBaseUrl();
	addTitle("chargingStationStatusDetails");
	search();
	setTimeout(hideLoading, 1500);
})

function search() {
	$ajax('realTimeChargingStationDetail', {ChargingStationID: $("#detailID", parent.document).val()}, searchChargingStationStatus, '', searchChargingStationStatus);
}
function searchChargingStationStatus(data){
	chargingStationStatusData = data && data.chargingStationStatus || [];
	if (chargingStationStatusData){
		allTable();
		if (chargingStationStatusData.onlineStatus) {
			time = 5000;
		} else {
			time = 10000;
		}
	}
	setTimeout(search, time);
}
function allTable(){
	if (!$("#detailOneBody").html()) {
		$("#chargingStationNameTitle").html(chargingStationStatusData.chargingStationName || '未获取到充电站详细数据');
		createDetailUlBody("detailOneBody", chargingStationRealTimeDetailTable, chargingStationStatusData, 1);
	}
	$("#requestDTTM").html(timeStamp2String(chargingStationStatusData.requestDTTM) || '-');
	$("#onlineStatus").html(chargingStationStatusData.onlineStatus ? '正常' : '断开');
	var equipmentCount = chargingStationStatusData && chargingStationStatusData.equipmentCount || 0;
	if (onLineCount != chargingStationStatusData.onLineCount) {
		onLineCount = chargingStationStatusData.onLineCount || 0;
		setCountStation('onLineCount', equipmentCount, onLineCount);
	}
	if (outputMaxPower == 0) {
		outputMaxPower = equipmentCount * 450;
	}
	// 功率曲线
	if (startEchart && chargingStationStatusData.onlineStatus) {
		var outputPower = [];
		var powerRate = [];
		if (chargingDate && (chargingDate.getDate() - (getSystemTime()).getDate() > 0)) {
			outputPowerData = [];
			powerRateData = [];
		}
		chargingDate = getSystemTime();
		var date = timeStamp2String(chargingDate.getTime());
		outputPower.push(chargingStationStatusData.requestDTTM || date);
		if (chargingStationStatusData.currentPowerTotal == 0) {
			outputPower.push(0);
		} else {
			outputPower.push(Number(chargingStationStatusData.currentPowerTotal).toFixed(2));
		}
		powerRate.push(chargingStationStatusData.requestDTTM || date);
		if (chargingStationStatusData.currentPowerTotal == 0) {
			powerRate.push(0);
		} else {
			powerRate.push(Number((chargingStationStatusData.currentPowerTotal/outputMaxPower)*100).toFixed(2));
		}
		outputPowerData.push(outputPower);
		powerRateData.push(powerRate);
		outputPower = [];
		powerRate = [];
		changeEchart();
	}
	var tbody = $("#equipmentDetalisTbody");
	if (tbody && tbody.length > 0) {
		tbody.html('');
		var $div = $('<div>').appendTo(tbody);
		$("<div class='chargingStationDetalisDiv marginBottom2Ten'> ").html('<div class="inlineBlock"><img style="height:50px;" src="static/images/equipmentCharging.png"/>充电中</div><div class="inlineBlock chargingStationStatus"> '+ 
				(chargingStationStatusData && chargingStationStatusData.equipmentChargingCount || 0) +'</div>').appendTo($div);
		$("<div class='chargingStationDetalisDiv marginBottom2Ten'>").html('<div class="inlineBlock"><img style="height:50px;" src="static/images/equipmentCharged.png"/>充电结束</div><div class="inlineBlock chargingStationStatus"> '+ 
				(chargingStationStatusData && chargingStationStatusData.equipmentChargedCount || 0) +'</div>').appendTo($div);
		$("<div class='chargingStationDetalisDiv marginBottom2Ten'>").html('<div class="inlineBlock"><img style="height:50px;" src="static/images/equipmentIdle.png"/>空闲</div><div class="inlineBlock chargingStationStatus"> '+ 
				(chargingStationStatusData && chargingStationStatusData.equipmentIdleCount || 0) +'</div>').appendTo($div);
		$("<div class='chargingStationDetalisDiv marginBottom2Ten'>").html('<div class="inlineBlock"><img style="height:50px;" src="static/images/equipmentFault.png"/>故障</div><div class="inlineBlock chargingStationStatus"> '+ 
				(chargingStationStatusData && chargingStationStatusData.equipmentFaultCount || 0) +'</div>').appendTo($div);
		var equipmentStatusList = chargingStationStatusData && chargingStationStatusData.equipmentStatusList || [];
		var length = equipmentStatusList.length;
		if (length > 0) {
			$("<div class='chargingStationDetalisDiv marginBottom2Ten'>").html('<div class="inlineBlock"><img style="height:50px;" src="static/images/equipmentOffline.png"/>断开</div><div class="inlineBlock chargingStationStatus"> ' + 
					(chargingStationStatusData && chargingStationStatusData.equipmentOfflineCount || 0) +'</div>').appendTo($div);
		} else {
			$("<div class='chargingStationDetalisDiv marginBottom2Ten'>").html('<div class="inlineBlock"><img style="height:50px;" src="static/images/equipmentOffline.png"/>断开</div><div class="inlineBlock chargingStationStatus"> ' + 
					(equipmentCount || 0) + '</div>').appendTo($div);
		}
		$div = $('<div>').appendTo(tbody);
		$("<div class='marginBottom2Ten'>").html("<label>充电桩详细:</label>").appendTo($div);
		if (equipmentCount == 0 && length == 0) {
			$("<div class='inlineBlock equipmentStatus'>").html("<a>无</a>").appendTo($div);
		} else if (equipmentCount > 0 && length == 0) {
			for (var l=1; l<=equipmentCount; l++) {
				$("<div class='inlineBlock equipmentStatus marginBottom2Ten'>").html('<a><img style="height:50px;" src="static/images/equipmentOffline.png"/>' + ("#" + l) + '</a>').appendTo($div);
			}
		} else {
			var img = undefined;
			for (var m=0; m<length; m++) {
				if (chargingStationStatusData.equipmentStatusList[m].equipmentStatus == "充电中") {
					img = '<img style="height:50px;" src="static/images/equipmentCharging.png"/>';
				} else if (chargingStationStatusData.equipmentStatusList[m].equipmentStatus == "充电结束") {
					img = '<img style="height:50px;" src="static/images/equipmentCharged.png"/>';
				} else if (chargingStationStatusData.equipmentStatusList[m].equipmentStatus == "空闲") {
					img = '<img style="height:50px;" src="static/images/equipmentIdle.png"/>';
				} else if (chargingStationStatusData.equipmentStatusList[m].equipmentStatus == "断开") {
					img = '<img style="height:50px;" src="static/images/equipmentOffline.png"/>';
				} else if (chargingStationStatusData.equipmentStatusList[m].equipmentStatus == "故障") {
					img = '<img style="height:50px;" src="static/images/equipmentFault.png"/>';
				}
				if (chargingStationStatusData.equipmentStatusList[m].equipmentStatus == "断开") {
					$("<div class='inlineBlock equipmentStatus marginBottom2Ten'>").html('<a><img style="height:50px;" src="static/images/equipmentOffline.png"/>' + ("#" + (m + 1)) + '</a>').appendTo($div);
				} else {
					$("<div class='inlineBlock equipmentStatus marginBottom2Ten'>>").html('<a id="' + ("equipment" + (m + 1)) + '" href="#" onclick="showEquipmentStatus(' + 
							"'" + (chargingStationStatusData.equipmentStatusList[m].equipmentID) + "'" + ');return false;">' + 
							(img + "#" + (m + 1)) + "</a>").appendTo($div);
				}
			}
		}
	}
	if (tableRefresh) {
		tableRefresh = false;
		tbody = $("#securityTable");
		if (tbody && tbody.length > 0) {
			tbody.html('');
			var cameraCount = chargingStationStatusData && chargingStationStatusData.cameraCount || 0;
			var $div = $('<div>').appendTo(tbody);
			$("<div class='inlineBlock securityStatus marginBottom2Ten details' onclick='showScreen(" + '"in"' + ");return false;' onMouseOver=\"showImages('cameraTwo', 'cameraOne', this);\""+
					" onMouseOut=\"showImages('cameraOne', 'cameraTwo', this);\">").html(
					'<a id="inCamera" href="#">' + 
					'<img id="cameraOne" style="height:40px;" src="static/images/cameraGreen.png"/>'+
					'<img id="cameraTwo" class="displayNone" style="height:40px;" src="static/images/cameraWhite.png"/> 入口</a>').appendTo($div);
			$("<div class='inlineBlock securityStatus marginBottom2Ten details' onclick='showScreen(" + '"out"' + ");return false;'  onMouseOver=\"showImages('cameraIdTwo', 'cameraIdOne', this);\""+
					" onMouseOut=\"showImages('cameraIdOne', 'cameraIdTwo', this);\">>").html(
					'<a id="outCamera" href="#">'+
					'<img id="cameraIdOne" style="height:40px;" src="static/images/cameraGreen.png"/>'+
					'<img id="cameraIdTwo" class="displayNone" style="height:40px;" src="static/images/cameraWhite.png"/> 出口</a>').appendTo($div);
			for (var i=1; i<=cameraCount; i++) {
				$("<div class='inlineBlock securityStatus marginBottom2Ten'>").html("<a href='#' onclick='showScreen(" + i + ");return false;'>" + i + "</a>").appendTo($div);
			}
			$div = $('<div>').appendTo(tbody);
			$("<div class='marginBottom2Ten'>").html("桩-摄像头：").appendTo($div);
			if (equipmentCount == 0) {
				$("<div class='inlineBlock equipmentStatus marginBottom2Ten'>").html("<a>无</a>").appendTo($div);
			} else {
				for (var j=1; j<=equipmentCount; j++) {
					$("<div class='inlineBlock equipmentStatus marginBottom2Ten'>").html("<a id='" + "eCamera" + j +
							"' href='#' onclick='showScreen(" + j + ");return false;'><img style='height:40px;' src='static/images/cameraBlue.png'/>"
							+ ("#" + j) + "</a>").appendTo($div);
				}
			}
		}
		tbody = $("#parkTable");
		if (tbody && tbody.length > 0) {
			tbody.html('');
			var $div = $('<div class="marginBottom2Ten stallStatus">').appendTo(tbody);
			$("<div class='inlineBlock'>").html("<span style='font-size:24px;color:#FE902F;'>空闲</span> / 总").appendTo($div);
			$("<div class='inlineBlock' style='margin: 0 5px;'>").html("<span style='border:1px solid #ECECEC'></span>").appendTo($div);
			$("<div class='inlineBlock'>").html("<span style='font-size:24px;color:#FE902F;'>" + equipmentCount + "</span><span>/" + equipmentCount + "</span>").appendTo($div);
			$div = $('<div>').appendTo(tbody);
			$("<div class='marginBottom2Ten'>").html("车位详细：").appendTo($div);
			if (equipmentCount == 0) {
				$("<div class='inlineBlock equipmentStatus marginBottom2Ten'>").html("无").appendTo($div);
			} else {
				for (var k=1; k<=equipmentCount; k++) {
//					$("<div>").html("#" + k).appendTo($div).css({width: "5%", "line-height": "40px"});
					$("<div class='inlineBlock equipmentStatus marginBottom2Ten'>").html('<img style="width:50px;height:30px;" src="static/images/busPark.png"/>').appendTo($div);
				}
			}
		}
	}
	createDetailUlBody("detailFiveBody", chargingStationRealTimeDetailTable, chargingStationStatusData, 2);
	createDetailUlBody("detailSixBody", chargingStationRealTimeDetailTable, chargingStationStatusData, 3);
	createDetailUlBody("detailSevenBody", chargingStationRealTimeDetailTable, chargingStationStatusData, 4);
	createDetailUlBody("detailEightBody", chargingStationRealTimeDetailTable, chargingStationStatusData, 5);
	if (chargingStationStatusData && chargingStationStatusData.chargingStationName) {
		$("#chargingStationName").html('<a class="details" onclick=\'chargingStationName("0")\'>'+chargingStationStatusData.chargingStationName+'</a>')
	}
	$("#chargingCountDay").html('');
	$("#chargingDegreeDay").html('');
	$("#currentPowerTotal").html('');
	$("#chargingCountDay").html(chargingStationStatusData.chargingCountDay);
	$("#chargingDegreeDay").html(chargingStationStatusData.chargingDegreeDay);
	$("#currentPowerTotal").html(chargingStationStatusData.currentPowerTotal);
	setFormDisabled("chargingStationDetailForm");
}
function chargingStationName(num){
	window.parent.detalisDrop('chargingStation/chargingStationDetail', num, $("#currentPage").val(), "drownDown1", "" ,"chargingStationPage" ,"chargingStation");
	$("#parentSkipMenu", parent.document).val("chargingStationPage");
	$("#detailID", parent.document).val(chargingStationStatusData[num].chargingStationID);
}
function showEquipmentStatus(equipmentID) {
	window.parent.skipMenu('chargingEquipment/equipmentRealTimeDetail', 'drownDown2', '', 'equipmentPage', 'equipmentRealTimeStatus');
	$("#parentSkipMenu", parent.document).val("chargingStationPage")
	$("#chargingStationID", parent.document).val($("#detailID", parent.document).val());
	$("#detailID", parent.document).val(equipmentID);
}
function goback() {
	if ($("#parentSkipMenu", parent.document).val() == "homePage") {
		window.parent.skipMenu('chargingStation/chargingStationMap', '', '', 'homePage');
	} else if ($("#parentSkipMenu", parent.document).val() == "chargingStationPage") {
		window.parent.skipMenu('chargingStation/chargingStationStatus', 'drownDown1', '', 'chargingStationPage', 'chargingStationStatus');
	}
}
function showScreen(index){
	webcamIndex = index;
	$("#canvas").hide();
	$("#saveImageBtn").hide();
	$("#camera1").empty();
	$("#canvas").empty();
	var title = "】摄像头";
	if (index == "in") {
		$("#cameraTitle").html("【入口" + title);
	} else if (index == "out") {
		$("#cameraTitle").html("【出口" + title);
	} else {
		$("#cameraTitle").html("【#" + index + "充电桩" + title);
	}
	$("#cameraDialog").draggable(
		{cancel: "#camera1", }
	);
	var pos = 0, image = [];
	$("#camera1").webcam({
	    width: "100%",
	    height: 225,
	    mode: "callback",
	    swffile: "static/webcam/jscam.swf",
	    onTick: function() {},//定时触发，定时拍照
	    onSave: function(data) {
			image.push(data);
			pos += 4*320;
			if (pos >= 4*320*240) {
				showImage(image);
				pos = 0;
			}
		},
	    onCapture: function() {
			webcam.save();
			image = [];
		},
	    debug: function() {},
	    onLoad: function() {}
	});
//	preview();
	$("#camera").modal("show");
//	showMessge(messageContent["Webcam.NotConnect"]);
}
function showImages(ImageOne, ImageTwo, object){
	if (ImageOne) {
		$('#' + ImageOne).show();
	}
	if (ImageTwo) {
		$('#' + ImageTwo).hide();
	}
}
function showImage(data){
	$("#canvas").show();
	$("#saveImageBtn").show();
	var canvas = document.getElementById("canvas");
//	canvas.setAttribute('width', 320);
//	canvas.setAttribute('height', 240);
	var ctx = canvas.getContext("2d");
	var image = ctx.getImageData(0, 0, 320, 240);
	var length = data && data.length || 0;
	var col = undefined;
	var tmp = undefined;
	var pos = 0;
	for(var i=0; i<length; i++) {
		col = data[i] && data[i].split(";");
		for (var j = 0; j<320; j++){
			tmp = parseInt(col[j], 10);
			image.data[pos + 0] = (tmp >> 16) & 0xff;
			image.data[pos + 1] = (tmp >> 8) & 0xff;
			image.data[pos + 2] = tmp & 0xff;
			image.data[pos + 3] = 0xff;
			pos += 4;
		}
	}
	ctx.putImageData(image, 0, 0);
}
function exitHikvision(){
	$("#camera").modal("hide");
//	stopPreview();
}
function capture(){
	webcam.capture();
}
function saveImage(){
	var data = {
		type:"data", 
		image: canvas.toDataURL("image/png"),
		chargingStationID: chargingStationStatusData.chargingStationID,
		webcamID: webcamIndex
	}
	$ajaxCommon("saveWebcamImage", saveImageReslut, data);
}
function saveImageReslut(data){
	var result = data && data.result;
	if (result == "ChargingStationIDNull" || result == "WebcamIDNull") {
		showMessge(messageContent["Webcam.SavePathError"]);
	} else if (result == "ImageNull") {
		showMessge(messageContent["Webcam.NotFound"]);
	} else if (result == "Success") {
		$("#saveImageBtn").hide();
		$("#canvas").hide();
		$("#canvas").empty();
		showMessge(messageContent["Webcam.Success"]);
	} else {
		showMessge(messageContent["Webcam.Error"]);
	}
}
function showEchart(){
	$("#pwrOn").toggle();
	$("#pwrOff").toggle();
	$("#echart").toggle();
	if(!$("#histogram").html()){
		chargingChart = echarts.init(document.getElementById('histogram'));
		chargingChart.showLoading({text : "功率曲线加载中..."});
		$ajax('realTimeCharging', {ChargingStationID: $("#detailID", parent.document).val(), chargingType: "STATION"}, searchChargingStatus, '', searchChargingStatus);
	}
}
function searchChargingStatus(data){
	if (data.outputMaxPower && data.outputMaxPower > 0) {
		outputMaxPower = data.outputMaxPower;
	}
	if(data && data.outputPower && data.outputPower.length > 0){
		var length = outputPowerData.length;
		var tempOutputPowerData = data.outputPower || [];
		var tempPowerRateData = data.powerRate || [];
		if(length > 0){
			for(var i = 0; i < length; i++){
				if(outputPowerData[i][0] > tempOutputPowerData[tempOutputPowerData.length - 1][0]){
					tempOutputPowerData.push(outputPowerData[i]);
					tempPowerRateData.push(powerRateData[i]);
				}
			}
		}
		outputPowerData = tempOutputPowerData;
		powerRateData = tempPowerRateData;
	}
	setTimeout(function (){chargingChart.hideLoading();}, 200);
	startEchart = true;
	changeEchart();
}
function changeEchart(){
	var option = {
			tooltip : {
				trigger: 'axis',
				axisPointer:{
            		label: {
            			formatter: function (params) {
            				if (params && params.value) {
            					return timeStamp2String(new Date(params.value)).substr(5);
            				} else {
            					'时间异常';
            				}
            			}
            		}
            	}
			},
			legend: {
            	x: 'right',
                data:['充电站功率','充电站利用率']
            },
			dataZoom: {
				show: true
			},
			xAxis: [
				{
					type: 'time',
					name: '时间',
					min: date2String(getSystemTime().getTime()) + " 00:00:00",
					max: (outputPowerData && outputPowerData[outputPowerData.length - 1] && outputPowerData[outputPowerData.length - 1][0]) || '',
					splitNumber: outputPowerData && outputPowerData.length && outputPowerData.length < 10 ? outputPowerData && outputPowerData.length : 10,
					axisLabel: {
						formatter : function (chargingTime) {
							if(chargingTime){
                				return timeStamp2String(new Date(chargingTime)).substr(11);
                			} else {
                				return '';
                			}
						}
					}
				}
			],
			yAxis: [
				{
					type: 'value',
					name: '充电站功率',
					min: 0,
					max: outputMaxPower,
					position: 'left',
					axisLine: {
                        lineStyle: {
                            color: '#43d3ff',
                        }
                    },
					axisLabel: {
						formatter: '{value}'
					}
				},
                {
                    type: 'value',
                    name: '充电站利用率',
                    min: 0,
                    max: 100,
                    show: false,
                    position: 'right',
                    axisLine: {
                        lineStyle: {
                            color: '#fe902f',
                        }
                    },
                    axisLabel: {
                        formatter: '{value}'
                    }
                }
			],
			series: [
				{
					name:'充电站功率',
					type:'line',
					symbol:'none',
					itemStyle: {
						normal : {
							color: '#43d3ff',
							areaStyle: {type: 'default'}
						}
					},
					data:outputPowerData
				},
                {
                    name:'充电站利用率',
                    type:'line',
                    symbol:'none',
                    yAxisIndex:1,
                    itemStyle: {
                        normal : {
                            color: '#fe902f',
                            areaStyle: {type: 'default'}
                        }
                    },
                    data:powerRateData
                }
			]
		};
	chargingChart.setOption(option);
}
function setCountStation(countID, allCount, onLineCount){
    var option = {
        tooltip : {
            formatter: "{a} <br/> {c}"
        },
        toolbox: {
            show : true,
        },
        series : [
            {
                name: '在线桩数量:',
                type: 'gauge',
				min: 0,
				max: allCount,
                startAngle: 180,
                endAngle: 0,
                splitNumber: allCount || 1,       // 分割段数，默认为5
                axisLine: {            // 坐标轴线
                    lineStyle: {       // 属性lineStyle控制线条样式
                        color: [[onLineCount/(allCount || 1), '#09BE09'],[1, '#DDD']],
                        width: 25
                    }
                },
                axisTick: {            // 坐标轴小标记
                    splitNumber: 10,   // 每份split细分多少段
                    length :12,        // 属性length控制线长
                    lineStyle: {       // 属性lineStyle控制线条样式
                        color: 'auto'
                    }
                },
                axisLabel: {           // 坐标轴文本标签，详见axis.axisLabel
                    textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                        color: 'auto'
                    }
                },
                splitLine: {           // 分隔线
                    show: false,        // 默认显示，属性show控制显示与否
                    length :-25,         // 属性length控制线长
                    lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
                        color: 'auto'
                    }
                },
                pointer : {
                    width : 0
                },
                title : {
                    show : true,
                    offsetCenter: [0, '-10%'],       // x, y，单位px
                    textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                        fontWeight: 'bolder'
                    }
                },
                detail : {
                  formatter:'{value}',
                  offsetCenter: [0, -50],
                  name: '在线桩数量',
                    textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                        color: 'auto',
                        fontWeight: 'bolder',
                        fontSize: 40
                    }
                },
                data:[{value: onLineCount, name: '在线桩数量'}]
            }
        ]
    };
    // 为echarts对象加载数据 
    echarts.init(document.getElementById(countID)).setOption(option);
}